package client;

import general.MarketeerClientInterface;
import general.Product;

import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;

import net.jini.core.lookup.ServiceItem;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.discovery.LookupDiscoveryManager;
import net.jini.lease.LeaseRenewalManager;
import net.jini.lookup.ServiceDiscoveryManager;

public class Client {
	
	private MarketeerClientInterface fMarketeerProxy;
	
	public Client() {
		
		// Install security manager
		System.setProperty("java.security.policy", "config/client.policy");
		System.setSecurityManager(new RMISecurityManager());
		
		try {
		
			// Get lookup service
			LookupDiscoveryManager discoveryMgr = new LookupDiscoveryManager(new String [] {"JORSEBREGGIE"}, null, null);
			ServiceDiscoveryManager serviceMgr = new ServiceDiscoveryManager(discoveryMgr, new LeaseRenewalManager());

			// Search for MarketPlaceMarketeer service
			Class[] classes = new Class[] { MarketeerClientInterface.class }; 
			ServiceTemplate template = new ServiceTemplate(null, classes, null);
			ServiceItem item = null;
			item = serviceMgr.lookup(template, null, 1000L);

			// Get the service
			if (item == null) {
				System.out.println("MarketeerClient service not found"); 
				System.exit(1);
			}
			fMarketeerProxy = (MarketeerClientInterface) item.service;
			if (fMarketeerProxy == null) { 
				System.out.println("MarketeerClient service not found"); 
				System.exit(1);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		
		System.out.println("Client started...");
	}
	
	public void addProduct(Product product) {
		try {
			fMarketeerProxy.addProduct(product);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
}
